package com.data.mall.etl.service.impl;

import com.data.mall.etl.domain.EventParams;
import com.data.mall.etl.domain.enums.Event;
import com.data.mall.etl.domain.enums.Params;
import com.data.mall.etl.dto.EventParamsDTO;
import com.data.mall.etl.dto.ParamsDTO;
import com.data.mall.etl.repository.EventParamsRepository;
import com.data.mall.etl.service.EventParamsService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @author shixukai
 * @Package com.data.mall.etl.service.impl
 * @Description: TODO
 * @date 2021/5/4
 */
public class EventParamsServiceImpl implements EventParamsService {
    @Autowired
    EventParamsRepository eventParamsRepository;

    @Override
    public void save(EventParamsDTO dto) {
        if(checkEventParams(dto.getEvent())){
            eventParamsRepository.deleteAll(eventParamsRepository.findAllByEvent(dto.getEvent().name()));
        }
        for(Params param:dto.getParamList()){
            eventParamsRepository.save(EventParams.builder().event(dto.getEvent().name()).eventName(dto.getEvent().getName()).name(param.name()).paramName(param.getName()).build());
        }
    }

    @Override
    public EventParamsDTO selectByEvent(Event event) {
        List<EventParams> eventParams = eventParamsRepository.findAllByEvent(event.name());
        List<Params> paramsList = new ArrayList<>();
        for(EventParams params: eventParams){
            paramsList.add(Params.of(params.getName()));
        }
        return EventParamsDTO.builder().event(event).paramList(paramsList).build();
    }

    private boolean checkEventParams(Event event){
        int count = eventParamsRepository.countAllByEvent(event.name());
        if(count >0){
            return false;
        }
        return true;
    }
}
